package m.app.action;

import m.app.service.AppLoginService;
import m.app.util.WxServerApiUtil;
import m.base.model.AppInfo;
import m.base.model.UserInfo;
import m.base.service.StoreInfoService;
import m.base.service.UserInfoService;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.model.type.FieldType;
import m.common.model.util.ModelQueryCheck;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.html.element.other.DisplayItem;
import m.store.model.GuestInfo;
import m.system.RuntimeData;
import m.system.cache.CacheUtil;
import m.system.document.DocumentMeta;
import m.system.document.DocumentMethodMeta;
import m.system.document.DocumentModelMeta;
import m.system.document.DocumentParamMeta;
import m.system.exception.MException;
import m.system.util.*;
import manage.model.StatusModel;
import manage.util.DictionaryUtil;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ActionMeta(name = "app/userInfo",title = "app用户信息")
public class UserInfoAction extends AppAction{
    private UserInfo model;
    @DocumentMeta(
        method = @DocumentMethodMeta(title = "获取微信openid"),
        params = {
            @DocumentParamMeta(name="code",description = "微信code",length = 50,notnull = true)
        }
    )
    @RequestMeta(params = {"code"})
    public JSONMessage getWxOpenId(String code) throws Exception {
        JSONMessage result= new JSONMessage(WxServerApiUtil.instance().getWmOpenInfo(code));
        return JSONMessage.success("").push("openid",result.get("openid"));
    }
    @DocumentMeta(
        method=@DocumentMethodMeta(title="获取小程序二维码",description=""),
        params={
            @DocumentParamMeta(name="wmPage",description="页面",type= FieldType.STRING,length=20,notnull=true),
            @DocumentParamMeta(name="scene",description="参数",type=FieldType.STRING,length=20,notnull=true),
        }
    )
    @RequestMeta(params= {"wmPage","scene"})
    public JSONMessage getWmUnlimited(String wmPage,String scene) {
        try {
            JSONMessage message= JSONMessage.success("获取成功");
            String p= RuntimeData.getFilePath()+"wmCode/"+DateUtil.format(new Date(),"yyyyMMdd")+"/";
            if(!FileUtil.existsWebFile(p+scene+".png")) {
                WxServerApiUtil util=WxServerApiUtil.instance();
                util.getWmUnlimited(wmPage, scene, 300,p,scene+".png");
            }
            message.push("path", RuntimeData.getStaticDomain() + p+scene+".png");
            return message;
        } catch (Exception e) {
            if(RuntimeData.getDebug()) e.printStackTrace();
            return JSONMessage.error("获取失败");
        }
    }
    /**
     * 进入app首先调用的方法
     */
    @DocumentMeta(
        method = @DocumentMethodMeta(title="获取用户信息",permission = true)
    )
    public JSONMessage getUserInfo() throws Exception {
        model=getService(AppLoginService.class).getUser(getAuthKey());
        if(null!=model)
            CacheUtil.pushLocal(getAuthKey(),model.getOid());
        return JSONMessage.success("").push("user",model);
    }
    @DocumentMeta(
        method = @DocumentMethodMeta(title="用户登录",permission = true),
        models = {
            @DocumentModelMeta(name="m.base.model.UserInfo",fieldNames = {"username","password"},notnull = {true,true})
        }
    )
    public JSONMessage userLogin() throws Exception {
        if(null==model) model=new UserInfo();
        ModelQueryCheck.init(model)
            .checkNotNull("username","请输入账号")
            .checkNotNull("password","请输入密码")
            .doCheck(false,true);
        model=getService(AppLoginService.class).userLogin(getAuthKey(),model.getUsername(),model.getPassword());
        return JSONMessage.success("登录成功").push("user",model);
    }
    @DocumentMeta(
        method = @DocumentMethodMeta(title = "退出登录",permission = true)
    )
    public JSONMessage userLogout() throws Exception {
        getService(AppLoginService.class).userLogout(getAuthKey());
        return JSONMessage.success("退出成功");
    }
    public JSONMessage getUserDict() throws Exception {
        List<DisplayItem> dhList= new ArrayList<>();
        ModelQueryList.getModelList(UserInfo.class,new String[]{"oid","realname"},null,
            QueryCondition.and(
                QueryCondition.eq("orgGroup.oid", PowerUtil.getSessionStoreOid()),
                QueryCondition.eq("status", StatusModel.Status_Enable)
            )
        ).forEach(item->dhList.add(DisplayItem.value(item.getOid(),item.getRealname())));
        return DictionaryUtil.toDictData(dhList);
    }
    @DocumentMeta(
        method = @DocumentMethodMeta(title = "员工列表",permission = true),
        params = {
            @DocumentParamMeta(name = "page.index",description = "分页开始位置",type = FieldType.INT),
            @DocumentParamMeta(name = "page.num",description = "分页每页数量",type = FieldType.INT),
            @DocumentParamMeta(name = "params[oid@eq]",description = "条件示例，字段和操作符中间用@，值为空不添加",type = FieldType.STRING,length = 50),
            @DocumentParamMeta(name = "params[oid#desc]",description = "排序示例，字段和操作符中间用#，值为空不生效",type = FieldType.STRING,length = 50)
        }
    )
    public JSONMessage getList() throws Exception {
        ModelQueryList queryList=toQueryList(UserInfo.class,"*","headImage.thumPath");
        queryList.addCondition(QueryCondition.eq("orgGroup.oid", PowerUtil.getSessionStoreOid()));
        queryList.addCondition(QueryCondition.not(QueryCondition.eq("oid","1")));
        return JSONMessage.success("查询成功").push("page",ModelQueryList.getModelPageInfo(queryList));
    }
    private void verifyUserNum() throws Exception {
        int userNum=getService(StoreInfoService.class).getStoreUserNum(PowerUtil.getSessionStoreOid());
        if(userNum>= LevelUtil.userNum()){
            throw new MException(this.getClass(),"用户数量已超过限制（当前商户级别限制用户数量："+LevelUtil.userNum()+"）");
        }
    }
    @DocumentMeta(
        method = @DocumentMethodMeta(title = "查询员工信息信息",permission = true),
        params = {
            @DocumentParamMeta(name = "model.oid",description = "员工oid",type = FieldType.STRING,length = 50)
        }
    )
    public JSONMessage getInfo() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Store);//权限判断
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*");
            model.setPassword("");
        }else{
            verifyUserNum();
            model=new UserInfo();
        }
        return JSONMessage.success("查询成功")
                .push("model",model);
    }


    public UserInfo getModel() {
        return model;
    }

    public void setModel(UserInfo model) {
        this.model = model;
    }
}
